package com.my.helper.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.my.helper.MainActivity;
import com.my.helper.R;
import com.my.helper.bean.LoginData;
import com.my.helper.bean.LoginRoot;
import com.my.helper.util.CacheActivity;
import com.my.helper.util.SharedPrefUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etUserName;
    private EditText etPassword;
    private Button btnLogin;
    private String strInputName;
    private String strInputPassword;
    private String strInputPasswordAgin;
    private RelativeLayout rlRegeste;
    private String loginUrl = "http://www.wanandroid.com/user/login";
    private String userId;
    private TextView tvRegister;
    private SharedPrefUtil sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = new SharedPrefUtil(this, "myHelper");
        setContentView(R.layout.activity_login);
        CacheActivity.addActivity(this);
        initView();
        initListener();
    }

    private void initView() {
        etUserName = findViewById(R.id.et_user_name);
        etPassword = findViewById(R.id.et_user_password);
        btnLogin = findViewById(R.id.btn_login_login);
        rlRegeste = findViewById(R.id.rl_regest);
        tvRegister = findViewById(R.id.tv_register_login);
    }

    private void initListener() {
        btnLogin.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String name = sp.getString("user_name", "001");
        if (name.equals("001")) {

        } else {
            etUserName.setText(name);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login_login: // 登录
                goLoginCheck();
                break;
            case R.id.tv_register_login: // 跳转注册
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 登录检查
     */
    private void goLoginCheck() {
        strInputName = etUserName.getText().toString();
        strInputPassword = etPassword.getText().toString();
        if (strInputName.isEmpty()) {
            ToastUtil("请输入用户名");
        } else if (strInputName.length() < 6) {
            ToastUtil("请输入6-16位的用户名");
        } else if (strInputPassword.isEmpty()) {
            ToastUtil("请输入密码");
        } else if (strInputPassword.length() < 6) {
            ToastUtil("请输入6-16密码");
        } else {
            goLogin();
        }
    }

    /**
     * 登录
     */
    private void goLogin() {
        OkHttpUtils
                .post()
                .url(loginUrl)
                .addParams("username", strInputName)
                .addParams("password", strInputPassword)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil("登录失败");
                        Log.i("bmw", "登录失败：" + e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("bmw", "登录成功：" + response);
                        Gson gson = new Gson();
                        String msgs = "登录失败";
                        String userName = etUserName.getText().toString();
                        int code;
                        try {
                            LoginRoot root = gson.fromJson(response, LoginRoot.class);
                            msgs = root.getErrorMsg();
                            code = root.getErrorCode();
                            LoginData data = root.getData();
                            userId = "" + data.getId();
                            sp.putString("user_id", userId);
                            sp.putString("user_name", userName);
                            sp.commit();
                            if (code == 0) {
                                // 登录成功
                                goIntent();
                            } else {
                                ToastUtil(msgs);
                            }
                        } catch (Exception e) {
                            Log.i("BMW", "登录解析失败");
                            Toast.makeText(LoginActivity.this, "用户名或密码不匹配", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 跳转界面
     */
    private void goIntent() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        CacheActivity.finishSingleActivityByClass(LoginActivity.class);
    }

    private void ToastUtil(String msg) {
        Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}
